package modules::cufflinks;

sub new {
  my ($class,$config,$fastq_1,$fastq_2) = @_;
  print " - Cufflinks v1.3.0 ---> $fastq_1\n";
  my $self = {
               _path         => $config->{'PATH'       },
               _job_name     => $config->{'JOB_NAME'   },
               _genome       => $config->{'GENOME'     },
               _gtf_file     => $config->{'GTF_FILE'   },
               _fastq_dir    => $config->{'FASTQ_DIR'  },
               _samples      => $config->{'SAMPLES'    },
             };
  bless $self,$class;
  return $self;
}

sub prepare {
  
  my ($self)        = @_;
  my $samples       = $self->{'_samples'    };
  my $path          = $self->{'_path'       };
  my $job_name      = $self->{'_job_name'   };
  my $job_dir       = $path       . '/results/' . $job_name;
  my $cufflinks_out = $job_dir    . '/Cufflinks/'  ;
  
  $self->{'_cufflinks_out'} = $cufflinks_out;
  
  mkdir  $cufflinks_out, 0777 unless(-d $cufflinks_out); chmod(0777, $cufflinks_out);

  foreach my $sample(@$samples){
    my    $sample_dir = $cufflinks_out. $sample->[0];
    mkdir $sample_dir, 0777 unless(-d $sample_dir); 
    print "Creating directory '$sample_dir'...\n";
    chmod(0777, $sample_dir);
  }
  return;
}

sub run {
  my ($self,$tophat_out)    = @_;
  my $samples               = $self->{'_samples'      };
  my $cufflinks_out         = $self->{'_cufflinks_out'};
  my $gtf_file              = $self->{'_gtf_file'     };
  my $i=1;
  
  foreach my $sample(@$samples) {   
    my $cmd  = qq(bsub -J cufflinks_$i -n 4 -R "span[ptile=4] rusage[mem=5000]" cufflinks-1.3.0 cufflinks )
           . qq(-o $cufflinks_out/$sample->[0] -p 8 -g $gtf_file )
           . qq($tophat_out/$sample->[0]/accepted_hits.bam); 
    print "\n\nRUNNING COMMAND:\n$cmd\n\n";
    system($cmd);
    $i++;
  }
  my $wait = 1;
  while ($wait == 1) {
    my  @info = qx(bjobs);
    print scalar localtime() . "\n";
    if(my @cufflinks_jobs = grep(/links_/, @info) ) { map{print $_}@cufflinks_jobs; sleep 10 }
    else {$wait = 0}  
  }  
  
}
1; 

